package com.stylefeng.guns.modular.doorLogs.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.core.base.controller.BaseController;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import com.stylefeng.guns.modular.system.model.Record;
import com.stylefeng.guns.modular.doorLogs.service.IRecordService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 控制器
 *
 * @author fengshuonan
 * @Date 2018-10-08 19:19:38
 */
@Controller
@RequestMapping("/record")
public class RecordController extends BaseController {

    private String PREFIX = "/doorLogs/record/";
    Logger logger = LoggerFactory.getLogger(RecordController.class);
    @Autowired
    private IRecordService recordService;

    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "record.html";
    }

    /**
     * 跳转到添加
     */
    @RequestMapping("/record_add")
    public String recordAdd() {
        return PREFIX + "record_add.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("/record_update/{recordId}")
    public String recordUpdate(@PathVariable Integer recordId, Model model) {
        Record record = recordService.selectById(recordId);
        model.addAttribute("item",record);
        LogObjectHolder.me().set(record);
        return PREFIX + "record_edit.html";
    }

    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list( String name,String cardNo,String status,String doorNumber,String inOrGo,String beginTime,String endTime) throws Exception{

        if (name==null&&cardNo==null&&status==null&&beginTime==null&&endTime==null){
            return recordService.selectList(null);
        }else {
            EntityWrapper<Record> wrapper = new EntityWrapper<>();
            if (name!=null){
                wrapper.like("name",name);
            }
            if (cardNo!=null){
                wrapper.like("cardno",cardNo);
            }
           if (status!=null){
               wrapper.like("note1",status);
           }
            if (doorNumber!=null){
                wrapper.like("note2",doorNumber);
            }
            if (inOrGo!=null){
                wrapper.like("note3",inOrGo);
            }
           if (beginTime!=null&&beginTime!=""&&endTime!=null&&endTime!=""){
               wrapper.between("time",beginTime,endTime);
           }
            return recordService.selectList(wrapper);
        }
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Record record) {
        recordService.insert(record);
        return SUCCESS_TIP;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer recordId) {
        recordService.deleteById(recordId);
        return SUCCESS_TIP;
    }
    /**
     * 清空
     */
    @RequestMapping(value = "/deleteAll")
    @ResponseBody
    public Object deleteAll() {
        recordService.deleteAll();
        return SUCCESS_TIP;
    }
    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Record record) {
        recordService.updateById(record);
        return SUCCESS_TIP;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{recordId}")
    @ResponseBody
    public Object detail(@PathVariable("recordId") Integer recordId) {
        return recordService.selectById(recordId);
    }

    /**
     * 下载打卡信息
     */
    @RequestMapping(value = "/download")
    @ResponseBody
    public void download(HttpServletResponse response) throws IOException {

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("打卡信息表");

//        List<CarInfo> listCar = carInfoService.getCarInfo(info.getPlateNumber(),info.getType(),info.getStatus());
        List<Record> recordList = recordService.selectList(null);
        String fileName = "打卡信息表"  + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据

        int rowNum = 1;

        String[] headers = { "编号", "姓名", "卡号", "打卡时间","报警状态","预留1","预留2","预留3"};//headers表示excel表中第一行的表头

        HSSFRow row = sheet.createRow(0);//在excel表中添加表头

        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Record record : recordList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(record.getId());
            row1.createCell(1).setCellValue(record.getName());
            row1.createCell(2).setCellValue(record.getCardno());
            row1.createCell(3).setCellValue(record.getTime());
            row1.createCell(4).setCellValue(record.getNote1());
            row1.createCell(5).setCellValue(record.getNote2());
            row1.createCell(6).setCellValue(record.getNote3());
            row1.createCell(7).setCellValue(record.getDateTime());
            rowNum++;
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        System.out.println("测试导出excel");
        workbook.write(response.getOutputStream());
    }

    /**
     *   ehart图表
     **/
    @RequestMapping(value = "/selectList")
    @ResponseBody
    public Object selectList() {
        logger.info("查询echart=====================================================");
        Wrapper<Record> wrapper=new EntityWrapper<Record>();
        Date data =new Date();
        DateFormat format =new SimpleDateFormat("yyyy-MM-dd");
        String time=format.format(data);
        wrapper.like("time",time).and(" note1 like '%开门成功%'");
        int carInfo =recordService.selectCount(wrapper);
        Wrapper<Record> wrapper1=new EntityWrapper<Record>();
        wrapper1.like("time",time).and("note1 like '%开门失败%'");
        int carInfo1 =recordService.selectCount(wrapper1);
        List a=new ArrayList();
        a.add(carInfo);
        a.add(carInfo1);
        logger.info("===============================================,a={}",a.toString());
        return a;
    }
}
